package com.cloud.pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;
import static org.openqa.selenium.support.ui.ExpectedConditions.textToBePresentInElement;

public class LoginPage extends AnyPage {

    //Constructor
    public LoginPage(PageManager pages) {
        super(pages);
    }


    //Variables
    private String loginPageTitle = "Sign in - Swivl";


    //Page elements
    @FindBy(id = "username")
    private WebElement emailField;

    @FindBy(id = "password")
    private WebElement passwordField;

    @FindBy(id = "_submit")
    private WebElement submitButton;

    @FindBy(id = "remember_me")
    private WebElement rememberMeCheckbox;

    @FindBy(xpath = "//*[@id=\"fixedContainer\"]/div[3]/div[2]/div")
    private WebElement notRecognizeError;


    //Methods
    public LoginPage ensurePageLoaded() {
        wait.until(presenceOfElementLocated(By.id("remember_me")));
        return this;
    }

    public boolean isLoaded() {
        try {
            wait.until(presenceOfElementLocated(By.id("remember_me")));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean checkNotRecognizeErrorIsDisplayed() {
        try {
            wait.until(textToBePresentInElement(notRecognizeError,
                    "We do not recognize your email and/or password. Please try again or click \"Forgot password?\" to restore your access."));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public LoginPage setEmailField(String text) {
        emailField.clear();
        emailField.sendKeys(text);
        return this;
    }

    public LoginPage setPasswordField(String text) {
        passwordField.clear();
        passwordField.sendKeys(text);
        return this;
    }

    public void clickSubmitButton() {
        submitButton.click();
    }

    public void selectKeepMeLoggedIn() {
        if(!rememberMeCheckbox.isSelected()) {
            rememberMeCheckbox.click();
        }
    }

    public String getLoginPageTitle() {
        return loginPageTitle;
    }

}
